package cn.fu.security.des;

import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**   
* @Title: My3DES.java 
* @Package cn.fu.security.des 
* @Description: 对称加密 :3重DES, 效率低，不如aes
* @author zhangxiaofu   
* @Company www.viewhigh.com
* @date 2016年8月21日 下午3:35:18 
* @version V1.0   
*/
public class My3DES {

	private static String src = "99fu";
	public static void main(String[] args) {
		bc3DES();
	}
	
	private static void bc3DES(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			//生成key
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede","BC");
//			KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");//默认为SunJCE version 1.7
			System.err.println(keyGenerator.getProvider());
//			keyGenerator.init(168);//长度
			keyGenerator.init(new SecureRandom());//默认长度的key,根据不同算法
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] bytesKey = secretKey.getEncoded();
			
			//key转换
			DESedeKeySpec desKeySpec = new DESedeKeySpec(bytesKey);
			SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
			Key convertSecretKey = factory.generateSecret(desKeySpec);
			
			//加密
			Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte [] result= cipher.doFinal(src.getBytes());
			System.err.println("bc3DES encrypt:" +Hex.encodeHexString(result));
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			System.err.println("bc3DES decrypt:"+new String(result));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

